package net.hn.hnms.biz.shipped.Listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.shipped.domain.TransportDeliveryInfo;
import net.hn.hnms.biz.shipped.mapper.TransportDeliveryInfoMapper;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
public class TransportDeliveryInfoListener implements ReadListener<TransportDeliveryInfo> {


    private static final int BATCH_COUNT = 100;
    private List<TransportDeliveryInfo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private TransportDeliveryInfoMapper transportDeliveryInfoMapper;

    @Override
    public void invoke(TransportDeliveryInfo data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        if(StrUtil.isBlank(data.getDeptName())||!data.getDeptName().equals("合计")){
            cachedDataList.add(data);
            // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (cachedDataList.size() >= BATCH_COUNT) {
                saveData();
                // 存储完成清理 list
                cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            }
        }



    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    public TransportDeliveryInfoListener(TransportDeliveryInfoMapper transportDeliveryInfoMapper) {
        this.transportDeliveryInfoMapper = transportDeliveryInfoMapper;
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));

        Set[] i = new Set[]{headMap.keySet()};
        Arrays.stream(i).forEach(set -> {
            log.info(set.toString());
        });
        for (Set set : i) {
            log.info(set.toString());
        }
        System.out.println();
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
//        userDao.save(cachedDataList);
        transportDeliveryInfoMapper.insertBatch(cachedDataList);
        log.info("存储数据库成功！");
    }
}
